import React from 'react'
import { useNavigate } from 'react-router-dom'
import { Card, Button, Checkbox, Form, Input, message } from 'antd'
import styles from './index.module.scss'
import logo from 'assets/logo.png'
import { login } from 'api/user'
import { setToken } from 'utils/storage'

export default function Login() {
  const navigate = useNavigate()
  return (
    <div className={styles.login}>
      <Card className='login-container'>
        <img src={logo} alt='' className='login-logo' />
        {/* 表单 */}
        <Form
          size='large'
          initialValues={{
            mobile: '13911111111',
            code: '246810',
            agree: true,
          }}
          onFinish={onFinish}
        >
          <Form.Item
            name='mobile'
            rules={[
              {
                required: true,
                message: '手机号不能为空',
              },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号格式错误',
              },
            ]}
          >
            <Input placeholder='请输入你的手机号' />
          </Form.Item>

          <Form.Item
            name='code'
            rules={[
              {
                required: true,
                message: '验证码不能为空',
              },
              {
                pattern: /^\d{6}$/,
                message: '验证码格式错误',
              },
            ]}
          >
            <Input placeholder='请输入验证码' />
          </Form.Item>

          <Form.Item
            valuePropName='checked'
            name='agree'
            rules={[
              {
                // 自定义校验规则
                // validator(rule, value) {
                //   if (value) {
                //     return Promise.resolve()
                //   } else {
                //     return Promise.reject(new Error('请阅读并且同意条款'))
                //   }
                // },
                validator: (rule, value) =>
                  value
                    ? Promise.resolve()
                    : Promise.reject(new Error('请阅读并且同意条款')),
              },
            ]}
          >
            <Checkbox>我已经阅读并且同意条款</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type='primary' htmlType='submit' block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )

  async function onFinish({ mobile, code }) {
    try {
      const res = await login(mobile, code)
      //登录成功，保存token
      setToken(res.data.token)
      // localStorage.setItem('token', res.data.token)
      //跳转到首页
      navigate('/layout/home')
      message.success('登录成功', 1)
    } catch (error) {
      message.warning(error.response.data.message, 1)
    }
  }
}
